<?php
class ModelToolSeoUrl extends Model {
    public function rewrite($link) {
        if ($this->config->get('config_seo_url')) {
            $url_data = parse_url(str_replace('&amp;', '&', $link));
           
            // Link does not containt query string.
            if(!isset($url_data['query'])){
                return $link;
            }
                        
            $url = '';   
            $data = array();           
            parse_str($url_data['query'], $data);
               
            if (isset($data['route'])){
                switch($data['route']){
                    case 'common/home':      
                        unset($data['route']);
                        return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']);
                        break;
                    case 'product/categories':                           
                        $url = $this->seoCategoryList($data);
                        break;
                    case 'product/category':                           
                        $url = $this->seoCategory($data);  
                        break;
                    case 'product/product':                           
                        $url = $this->seoProduct($data);    
                        break;
                    case 'product/manufacturer':   
                        $url = $this->seoManufacturerList($data);                         
                        break;
					case 'product/manufacturer/category':   
                        $url = $this->seoManufacturerCat($data);                         
                        break;
                    case 'product/manufacturer/viewManufacturer':                         
                        $url = $this->seoManufacturer($data); 
                        break;
                    case 'product/search':                           
                        $url = $this->seoSearch($data);    
                        break;
                    case 'content/list':
                        $url = $this->seoContentList($data); 
                        break;
                    case 'content/item':
                        $url = $this->seoContent($data); 
                        break;
                    case 'content/item/article':
                        $url = $this->seoContentArticle($data); 
                        break;
                    case 'information/information': 
                        $url = $this->seoInformation($data);                          
                        break;
                    case 'information/contact':  
                        $url = $this->seoInformationContact($data);                         
                        break;
                    case 'information/forhandlen':  
                        $url = $this->seoInformationService($data);                             
                        break;
                    case 'newsletter/newsletter':  
                        $url = $this->seoNewsletter($data);                             
                        break;
                    case 'checkout/giftcard':  
                        $url = $this->seoCheckoutGiftcard($data);                             
                        break; 
                }
            }    
              
            if ($url) {
                unset($data['route']);
            
                $query = '';                
                if ($data) {
                    foreach ($data as $key => $value) {
                        $query .= '&' . $key . '=' . $value;
                    }
                    
                    if ($query) {
                        $query = '?' . trim($query, '&');
                    }
                }

                return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
            }                         
            else {
                return $link;
            }
        } 
        else {
            return $link;
        }     
    }
    
    private function seoCategoryList(&$data){   
        $url    = '';
        $path   = '';        
        $key    = 'category_id';
        
        if(isset($data['path'])){            
            $path = $this->getPath($data['path']);   
            if($path){      
                $data_count = count(explode('_', $data['path']));
                $path_count = count(explode('/', trim($path, '/')));  
                
                if($data_count == $path_count){                 
                    $url = $path . '.html';
                                                          
                    unset($data['path']);
                }
            }    
        }
        else{
            $url = '/categories.html';
        }
            
        return $url;     
    }
    
    private function seoCategory(&$data){
        $url    = '';
        $path   = '';        
        $key    = 'category_id';
        
        if(isset($data['path'])){            
            $path = $this->getPath($data['path']);   
            if($path){      
                $data_count = count(explode('_', $data['path']));
                $path_count = count(explode('/', trim($path, '/')));  
                
                if($data_count == $path_count){                 
                    $url = $path . '.html';
                                                          
                    unset($data['path']);
                }
            }    
        }
            
        return $url;    
    }
        
    private function seoProduct(&$data){
        $url    = '';
        $path   = '';
        $page   = '';
        $key    = 'product_id';
        
        if(isset($data['path'])){
            $path = $this->getPath($data['path']);
            if($path){                
                unset($data['path']);
            }
        }
        
        $page = $this->getKeyword($key, $data[$key]); 
        if($page){
            $url = $path . $page;
            unset($data[$key]); 
        } 
        
        return $url;      
    }
    
    private function seoManufacturerList(&$data){ 
        $url    = '/manufacturers';
        $path   = '';
        
        if(isset($data['path'])){
            $path = $this->getPath($data['path']);
            if($path){                
                unset($data['path']);
            }
        } 
        
        return $url . $path . '.html'; 
    }
    
	private function seoManufacturerCat(&$data){ 
        $url    = '/manufacturer_category';
        $path   = '';
        
        if(isset($data['path'])){
            $path = $this->getPath($data['path']);
            if($path){                
                unset($data['path']);
            }
        } 
        
        return $url . $path . '.html'; 
    }
	
    private function seoManufacturer(&$data){
        $url    = '';
        $path   = '';
        $page   = '';
        $key    = 'manufacturer_id';
        
        if(isset($data['path'])){
            $path = $this->getPath($data['path']);
            if($path){                
                unset($data['path']);
            }
        }
        
        $page = $this->getKeyword($key, $data[$key]); 
        if($page){
            $url = $path . $page;
            unset($data[$key]); 
        } 
        
        return $url;      
    }
    
    private function seoSearch(&$data){
        return '/search.html';    
    }
    
    private function seoContentList(&$data){
        return '/list_article.html';    
    }
    
    private function seoContent(&$data){
        $url = ''; 
        $key = 'content_id';        
        
        $url = $this->getKeyword($key, $data[$key]); 
        if($url){
            unset($data[$key]); 
        } 
        
        return $url;      
    }
    
    private function seoContentArticle(&$data){
        $url = '';
        $key = 'content_id';        
        
        $page = $this->getKeyword($key, $data[$key]);
        if($page){
            $url .= '/article' . $page;
            unset($data[$key]); 
        } 
        
        return $url;    
    }
    
    private function seoInformation(&$data){
        $url = '';
        $key = 'information_id';        
        
        $url .= $this->getKeyword($key, $data[$key]);        
        if($url){
            unset($data[$key]); 
        } 
        
        return $url;    
    }
    
    private function seoInformationContact(&$data){
        return '/contact.html';    
    }
    
    private function seoInformationService(){
         return '/terms_and_conditions.html';    
    }
        
    private function seoNewsletter(&$data){
        return '/newsletter.html';    
    }
    
    private function seoCheckoutGiftcard(&$data){
        return '/giftcard.html';    
    }
    
    private function getKeyword($key, $value){
        $url = '';
        
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");                
        if ($query->num_rows) {
            $url .= '/' . $query->row['keyword']. '.html';                                                           
        }     
        
        return $url;
    }
    
    private function getPath($path){
        $url = '';
        
        if(isset($path)){
            $categories = explode('_', $path);
            
            foreach ($categories as $category) {
                $sql = "SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'";
                $query = $this->db->query($sql);
                
                if ($query->num_rows) {
                    $url .= '/' . $query->row['keyword'];
                }                            
            }  
        }    
        
        return $url; 
    }
    
    public function rewriteNew($link) {
        if ($this->config->get('config_seo_url')) {
            $url_data = parse_url(str_replace('&amp;', '&', $link));
        
            $url = '';                         
            $data = array();           
            parse_str($url_data['query'], $data);
            
            /*     
            if (isset($data['route'])){
                switch($data['route']){
                    case 'product/manufacturer':                           
                    break;
                    case 'content/list':
                    break;
                }
            }
            */
                    
            foreach ($data as $key => $value) {                 
                if (($key == 'product_id') || ($key == 'manufacturer_id') || ($key == 'information_id')) {
                    if (isset($data['path'])) {
                        $categories = explode('_', $data['path']);
                        
                        foreach ($categories as $category) {
                            $sql = "SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'";
                            $query = $this->db->query($sql);
                            
                            if ($query->num_rows) {
                                $url .= '/' . $query->row['keyword'];
                            }                            
                        }
                        
                        unset($data['path']);
                    } 
                    
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");                
                    if ($query->num_rows) {
                        $url .= '/' . $query->row['keyword']. '.html';
                        
                        unset($data[$key]);
                    }                   
                } 
                elseif ($key == 'content_id') {
                    if($data['route'] == 'content/item/article'){
                        $url .= '/article';    
                    }
                                    
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");                
                    if ($query->num_rows) {
                        $url .= '/' . $query->row['keyword']. '.html';
                        
                        unset($data[$key]);
                    }                   
                } 
                /*
                else{
                    if($data['route'] == 'information/contact'){
                        unset($data['route']);
                        $url = '/contact.html';   
                    }
                }               
                */
            }
        
            if ($url) {
                unset($data['route']);
            
                $query = '';    
            
                if ($data) {
                    foreach ($data as $key => $value) {
                        $query .= '&' . $key . '=' . $value;
                    }
                    
                    if ($query) {
                        $query = '?' . trim($query, '&');
                    }
                }

                return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
            } else {
                return $link;
            }
        } else {
            return $link;
        }        
    }
        
	public function rewriteOld($link) {
		if ($this->config->get('config_seo_url')) {
			$url_data = parse_url(str_replace('&amp;', '&', $link));
		
			$url = '';             			
			$data = array();
		
			parse_str($url_data['query'], $data);
			
			foreach ($data as $key => $value) {                 
				if (($key == 'product_id') || ($key == 'manufacturer_id') || ($key == 'information_id')) {
					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
				
					if ($query->num_rows) {
						$url .= '/' . $query->row['keyword'];
						
						unset($data[$key]);
					}					
				} elseif ($key == 'path') {
					$categories = explode('_', $value);
					
					foreach ($categories as $category) {
						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");
				
						if ($query->num_rows) {
							$url .= '/' . $query->row['keyword'];
						}							
					}
					
					unset($data[$key]);
				}  
			}
		
			if ($url) {
				unset($data['route']);
			
				$query = '';
			
				if ($data) {
					foreach ($data as $key => $value) {
						$query .= '&' . $key . '=' . $value;
					}
					
					if ($query) {
						$query = '?' . trim($query, '&');
					}
				}

				return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
			} else {
				return $link;
			}
		} else {
			return $link;
		}		
	}
}
?>